package com.jinke.api.modules.ums.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jinke.api.common.api.CommonPage;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.modules.app.enums.MemberType;
import com.jinke.api.modules.ums.dto.RoleUpdateParam;
import com.jinke.api.modules.ums.dto.UmsAdminListParam;
import com.jinke.api.modules.ums.dto.UmsAdminLoginParam;
import com.jinke.api.modules.ums.dto.UmsAdminParam;
import com.jinke.api.modules.ums.model.Channel;
import com.jinke.api.modules.ums.model.UmsAdmin;
import com.jinke.api.modules.ums.request.AllotChannelRequest;
import com.jinke.api.modules.ums.service.UmsAdminService;
import com.jinke.api.modules.ums.vo.UmsAdminVO;
import com.jinke.api.security.util.AdminUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 后台用户管理
 * Created by macro on 2018/4/26.
 */
@Controller
@Api(tags = "UmsStaffController")
@Tag(name = "员工管理", description = "员工管理")
@RequestMapping("/staff")
public class UmsStaffController {

    @Autowired
    private UmsAdminService adminService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation("根据用户名或姓名分页获取用户列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<UmsAdminVO>> list(UmsAdminListParam request) {
        request.setMemberType(MemberType.ADMIN);
        return adminService.listVo(request);
    }
    @ApiOperation(value = "用户注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<UmsAdmin> register(@Validated @RequestBody UmsAdminParam umsAdminParam) {
        umsAdminParam.setMemberType(MemberType.ADMIN);
        UmsAdmin umsAdmin = adminService.register(umsAdminParam);
        if (umsAdmin == null) {
            return CommonResult.failed();
        }
        return CommonResult.success(umsAdmin);
    }

    @ApiOperation("分配用户运输服务")
    @RequestMapping(value = "/channel/allot-channel", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<Channel>> allotChannel(@Validated @RequestBody AllotChannelRequest request) {
        request.setMemberType(MemberType.ADMIN);
        return adminService.allotChannel(request);
    }

    @ApiOperation("导出")
    @RequestMapping(value = "/down", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<String> down(UmsAdminListParam request) {
        request.setMemberType(MemberType.ADMIN);
        return adminService.down(request);
    }

    @ApiOperation("修改指定用户信息")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@PathVariable Integer id, @RequestBody UmsAdmin admin) {

        // 管理员可以修改余额

        UmsAdmin umsAdmin = getUmsAdmin(id);
        if (umsAdmin.getBalance().compareTo(admin.getBalance()) != 0) {
            if (!AdminUserUtil.getUserInfo().isAdmin()) {
                CommonResult.failed("非法操作");
            }
        }

        boolean success = adminService.update(id, admin);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @Nullable
    private UmsAdmin getUmsAdmin(Integer id) {
        UmsAdmin umsAdmin = adminService.getOne(new LambdaQueryWrapper<UmsAdmin>().eq(UmsAdmin::getId, id)
                .eq(UmsAdmin::getMemberType,MemberType.ADMIN)
        );
        if(umsAdmin == null){
            CommonResult.failed("非法操作");
        }
        return umsAdmin;
    }

    @ApiOperation("给用户分配角色")
    @RequestMapping(value = "/role/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateRole(@Validated @RequestBody RoleUpdateParam roleUpdateParam) {


        Integer adminId = roleUpdateParam.getAdminId();
        getUmsAdmin(adminId);
        int count = adminService.updateRole(adminId, roleUpdateParam.getRoleIds());
        if (count >= 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation(value = "登录以后返回token")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@Validated @RequestBody UmsAdminLoginParam umsAdminLoginParam) {
        String username = umsAdminLoginParam.getUsername();
        UmsAdmin umsAdmin = adminService.getOne(new LambdaQueryWrapper<UmsAdmin>().eq(UmsAdmin::getUsername,username)
                .eq(UmsAdmin::getMemberType,MemberType.ADMIN)
        );
        if(umsAdmin == null){
            CommonResult.failed("非法操作");
        }

        String token = adminService.login(username, umsAdminLoginParam.getPassword());
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }

        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);


        return CommonResult.success(tokenMap);
    }

    @ApiOperation("删除指定用户信息")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@PathVariable Integer id) {
        getUmsAdmin(id);

        boolean success = adminService.delete(id);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @ApiOperation("修改帐号状态")
    @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateStatus(@PathVariable Integer id, @RequestParam(value = "status") Integer status) {
        getUmsAdmin(id);
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setStatus(status);
        boolean success = adminService.update(id, umsAdmin);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @ApiOperation(value = "生成任意用户Token")
    @RequestMapping(value = "/token/build/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult buildToken(@PathVariable Integer id) {
        return  adminService.buildToken(id);
    }
}
